package com.wx.house.manager.api.permission.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.wx.house.common.base.BaseController;
import com.wx.house.core.pojo.base.Page;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.common.exception.BusinessException;

import com.wx.house.manager.api.permission.text.AdminPame;
import com.wx.house.manager.api.permission.text.AdminUpdate;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.wx.house.manager.api.permission.service.SysAdminRoleService;
import com.wx.house.manager.api.permission.service.SysAdminService;
import com.wx.house.manager.api.permission.text.AdminIDStateDto;
import com.wx.house.common.util.IDUtils;
import com.wx.house.common.util.JwtUtils;
import com.wx.house.common.util.StringUtil;
import com.wx.house.core.pojo.po.SysAdmin;
import com.wx.house.core.pojo.po.SysAdminRole;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("SysAdmin/")
@Api(value = "管理员模块", tags = "模块:管理员管理")
@Slf4j
public class SysAdminController extends BaseController{
@Resource
private SysAdminService sysAdminService;
@Resource
private SysAdminRoleService sysAdminRoleService;

/***
 * 管理员注册
 * @param adminTO
 * @param request
 * @return
 */
@ApiOperation(value = "添加用户", notes = "添加用户")
@PostMapping("addAdmin/")
public Result addAdmin(@RequestBody @Validated AdminPame adminPame, HttpServletRequest request) {
	try {
		String token = request.getHeader("authorization");
		//step1. 解析token
		Claims claims = JwtUtils.builder().token(token).build().claims();
		//step2. 从token获取参数,获取账号类型
		String accoutype = claims.get("accountType").toString();
		//step3. 从token获取参数,获取id
		String id= claims.get("id").toString();
		//step4. 从token获取参数,获取账号层级
		String level =claims.get("level").toString();
		//step4. 随机生成safakey
		Integer safeKey = IDUtils.getIntegerSafeKey();
		//step5. 获取循环次数
		String HASHITERATIONS = this.config("common.HASHITERATIONS");
		if (StringUtil.isNotEmpty(HASHITERATIONS)) {
			HASHITERATIONS = "1024";
		}
		//step6. 生成密码
		String pwd=new Sha256Hash(adminPame.getLoginPwd(), safeKey.toString(), Integer.parseInt(HASHITERATIONS)).toString();
		//传值
		sysAdminService.addAdmin(adminPame, pwd, safeKey,accoutype,level,id);
		return Result.success();
	} catch (Exception e) {
		throw new BusinessException("添加失败");
	}
}

@ApiOperation(value = "查询全部账号", notes = "查询全部账号")
@ApiImplicitParams({
	@ApiImplicitParam(name = "accountType", value = "角色类型", required = false, dataType = "String", paramType = "query")
})
@GetMapping("SelectAdmin/")
public Result<PageInfo<SysAdmin>> SelectAdmin(String accountType,Page page,HttpServletRequest request) {
	try {
		String token = request.getHeader("authorization");
		//step1. 解析token
		Claims claims = JwtUtils.builder().token(token).build().claims();
		//step2. 从token获取参数,获取账号等级
		String level = claims.get("level").toString();
		List<SysAdmin> sysAdmins= null;
		//判断账号等级
		if("0".equals(level))
		{	
			//超级管理员获取所有主账号
			 sysAdmins =sysAdminService.selectAdmin(null, accountType);
		}
		else {
			//查询主账号下的子账户
			 sysAdmins =sysAdminService.selectAdmin(level, accountType);
		}
		PageInfo<SysAdmin> pageInfo = new PageInfo<>(sysAdmins);
		return Result.success(pageInfo);
	} catch (Exception e) {
		throw new BusinessException("查询失败");
	}
}

@ApiOperation(value = "查询账号(手机号)是否被注册", notes = "查询账号(手机号)是否被注册")
@GetMapping("getAdminName/")
public Result getAdminName(String loginName) {
	try {
		SysAdmin admin=	sysAdminService.loginAdmin(loginName);
		if(StringUtil.isNotEmpty(admin))
		{
			return Result.error(null);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return Result.success(null);
}

@PutMapping("update/")
@ApiOperation(value = "更新用户", notes = "更新用户")
public Result updateAdmin(@RequestBody @Validated AdminUpdate adminUpdate, HttpServletRequest request) {
	try {
		String token = request.getHeader("authorization");
		//step1. 解析token
		Claims claims = JwtUtils.builder().token(token).build().claims();
		//step2. 从token获取参数,获取账号姓名
		String realName = claims.get("realName").toString();
		//step5 .存入SysAdmin
		SysAdmin sysAdmin =new SysAdmin();
		sysAdmin.setId(adminUpdate.getId());
		if (!StringUtils.isEmpty(adminUpdate.getRealName()))
		{
			sysAdmin.setRealName(adminUpdate.getRealName());
		}
		if (!StringUtils.isEmpty(adminUpdate.getPhone()))
		{
			sysAdmin.setPhone(Long.valueOf(adminUpdate.getPhone()));
			sysAdmin.setLoginName(adminUpdate.getPhone());
		}
		sysAdmin.setOperation(realName);
		sysAdmin.setOperationTime(new Date());
		sysAdminService.UpdateAdmin(sysAdmin);
		return Result.success();
	} catch (Exception e) {
		throw new BusinessException("更新失败");
	}
}

@ApiOperation(value = "禁用管理员(禁用1/启用0)", notes = "禁用管理员（传入的sysAdminId）")
@PutMapping("delete/")
public Result deleteAdmin(@RequestBody @Validated AdminIDStateDto adminIDStateDto,HttpServletRequest request) {
	try {
		String token = request.getHeader("authorization");
		//step1. 解析token
		Claims claims = JwtUtils.builder().token(token).build().claims();
		//step2. 从token获取参数,获取账号id
		String id = claims.get("id").toString();
		//判断是否是超级管理员
		if(id.equals(adminIDStateDto.getSysAdminId()))
		{
			throw new BusinessException("管理员不能禁用自己");
		}
		if("0".equals(adminIDStateDto.getState()))
		{
			sysAdminService.DeleteAdmin(adminIDStateDto.getSysAdminId(), 0 );
		}
		if("1".equals(adminIDStateDto.getState())) {
			sysAdminService.DeleteAdmin(adminIDStateDto.getSysAdminId(), 1 );
		}
		return Result.success();
	} catch (Exception e) {
		 throw new BusinessException("禁用/启用失败");
	}
}
@ApiOperation(value = "刪除用戶", notes = "刪除用戶（传入的sysAdminId）")
@DeleteMapping("deleteDelType/")
public Result deleteDelType(String sysAdminId,HttpServletRequest request) {
	try {
		String token = request.getHeader("authorization");
		//step1. 解析token
		Claims claims = JwtUtils.builder().token(token).build().claims();
		//step2. 从token获取参数,获取账号id
		String id = claims.get("id").toString();
		//判断是否是超级管理员
		if(id.equals(sysAdminId))
		{
			throw new BusinessException("管理员不能禁用自己");
		}
		sysAdminService.deleteDelType(sysAdminId);
		return Result.success();
	} catch (Exception e) {
		throw new BusinessException("删除失败");
	}
}


}
